package com.wanmait.recruitment.webController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.recruitment.pojo.*;
import com.wanmait.recruitment.pojo.Collection;
import com.wanmait.recruitment.service.*;
import com.wanmait.recruitment.pojo.Company;
import com.wanmait.recruitment.pojo.Deliver;
import com.wanmait.recruitment.pojo.Userinfo;
import com.wanmait.recruitment.service.*;
import com.wanmait.recruitment.util.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("zhuang")
public class UserinfoController {

    @Resource
    private ConfigService configService;
    @Resource
    private UserinfoService userinfoService;

    @Resource
    private DeliverService deliverService;
    @Resource
    private CompanyService companyService;
    @Resource
    private CollectionService collectionService;
    @Resource
    private MessageService messageService;
    @Resource
    private CycleService cycleService;
    @Resource
    private IndustryService industryService;
    @Resource
    private StageService stageService;
    @Resource
    private ProvinceService provinceService;
    @Resource
    private MoneyService moneyService;
    @Resource
    private SubscribeService subscribeService;
    @Resource
    private JobService jobService;

    @Autowired
    private JavaMailSender javaMailSender;
    private Logger logger = LogManager.getLogger(UserinfoController.class);
    private Map<String, Object> resultMap = new HashMap<>();
    @Value("${mail.fromMail.sender}")
    private String sender;// 发送者

    @Scheduled(cron = "0 0 0 * * ?")
    public void updateNowJobCount()
    {
        userinfoService.updatenowResumeCount();
    }
    @RequestMapping("user/delivery")
    public void delivery(HttpServletRequest request, Model model)
    {
        HttpSession session = request.getSession();
        Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
        Message message = new Message();
        message.setUserinfoId(userinfo.getId());
        message.setContent("投递");
        messageService.deleteUserId(message);
    }
    @RequestMapping("user/deliveryList")
    public void deliveryList(HttpServletRequest request,Model model,Integer state,Integer pagerNum)
    {
        int pagenum;
        try {
            pagenum =pagerNum;
        } catch (NumberFormatException e) {
            pagenum = 1;
        }
        //每页显示条数
        int pageSize;
        try {
         pageSize = Integer.parseInt(configService.getValueByKey("company_resume_count"));
        } catch (NumberFormatException e) {
           pageSize=5;
        }
        HttpSession session = request.getSession();
        Userinfo userinfo = (Userinfo) session.getAttribute("userinfo");
        PageInfo<Deliver>pageInfo = deliverService.findByUserId(pagenum,pageSize,userinfo.getId(),state);
        List<Deliver>delivers = pageInfo.getList();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("delivers",delivers);
    }
    @GetMapping("register")
    public  void register(){


    }
//    /**
//     *  校验激活码
//     * @param code
//     * @return
//     */
//    @RequestMapping("checkCode")
//    public String checkCode(String code){
//        Userinfo userinfo=userinfoService.getUserByActiveCode(code);
//        //User user = userService.getUserByActiveCode(code);
//        //如果用户不等于null，把用户状态修改status=1
//
//        if (userinfo !=null){
//            userinfo.setEnable(true);
//            //把code验证码清空，已经不需要了
//            userinfo.setActiveCode("");
//            userinfoService.modify(userinfo);
//
//            return "redirect:/aiticeSuccess.jsp";
//        }
//
//        return "zhuang/login";
//
//
//    }
//    /**
//     *  校验激活码
//     * @param code
//     * @return
//     */
//    @RequestMapping("checkCodeCompany")
//    public String checkCodeCompany(String code){
//        Company company=companyService.getUserByActiveCode(code);
//
//        //User user = userService.getUserByActiveCode(code);
//        //如果用户不等于null，把用户状态修改status=1
//
//        if (company!=null){
//            company.setEnable(true);
//            //把code验证码清空，已经不需要了
//            company.setActiveCode("");
//            companyService.modify(company);
//
//            return "redirect:/aiticeSuccess.jsp";
//        }
//
//        return "zhuang/login";
//
//
//    }

    //注册
    @PostMapping("register")
    public  String register(String work, String username, String passowrd, String email,String identify,RedirectAttributes attributes){
        System.out.println(identify);
        if (resultMap.size() ==0){
            return "zhuang/register";
        }
        System.out.println(identify);


            //判断验证码是否正确
            String requestHash = resultMap.get("hash").toString();

            String tamp = resultMap.get("tamp").toString();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");//当前时间
            Calendar c = Calendar.getInstance();
            String currentTime = sf.format(c.getTime());

            if (tamp.compareTo(currentTime) > 0) {
                String hash =  MD5Utils.code(identify);//生成MD5值
                if (hash.equalsIgnoreCase(requestHash)){
                    //校验成功
                    attributes.addFlashAttribute("m", "恭喜！现在，你可以登录你的用户名。");
                    if(Integer.parseInt(work)!=1) {
                        Company company = new Company();
                        company.setUsername(username);
                        company.setUserpass(passowrd);
                        company.setEmail(email);
                        companyService.register(company);


                    }
                    if(Integer.parseInt(work)==1) {
                        Userinfo userinfo = new Userinfo();
                        userinfo.setUsername(username);
                        userinfo.setUserpass(passowrd);
                        userinfo.setEmail(email);
                        userinfoService.register(userinfo);
                    }
                    return "redirect:/zhuang/login";

                }else {
                    //验证码不正确，校验失败
                    System.out.println("2");
                    attributes.addFlashAttribute("message", "验证码输入不正确");
                    return "redirect:/zhuang/register";
                }
            } else {
                // 超时
                System.out.println("3");
                attributes.addFlashAttribute("message", "验证码已过期");
                return "redirect:/zhuang/register";
            }






    }

    //验证公司用户名是否存在
    @RequestMapping("checkCompanyUsername")
    @ResponseBody
    public void checkCompanyUsername(String username,HttpServletResponse response) throws IOException {

        PrintWriter out=response.getWriter();
        if(companyService.checkUsername(username)!=null){
            out.print("1");
        }
        else {
            out.print("0");
        }

    }

    //验证用户名是否存在
    @RequestMapping("checkUsername")
    @ResponseBody
    public void checkUsername(String username , HttpServletResponse response) throws IOException {

        PrintWriter out=response.getWriter();
        if(userinfoService.checkUsername(username)!=null){
            out.print("1");
        }
        else {
            out.print("0");
        }
    }

    //登录页面
    @GetMapping("login")
    public void login()
    {

    }
    @RequestMapping("reset2")
    public void reset2()
    {

    }
    @RequestMapping("reset3")
    public String reset3(HttpServletRequest request,String type,String email,String userpass)
    {
        HttpSession session = request.getSession();
        Company company = (Company) session.getAttribute("company");
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        if (type.equals("1"))
        {
            companyService.updateUserPass(email,userpass);
            session.removeAttribute("company");
        }
        if (type.equals("0"))
        {
            userinfoService.updateUserPass(email,userpass);
            session.removeAttribute("userinfo");
        }
        return "redirect:/zhuang/login?msg=c";

    }

    //找回密码
    @GetMapping("reset")
    public void reset()
    {

    }
    @RequestMapping("sendEmail")
    @ResponseBody
    public String sendEmail(String email) {

        SimpleMailMessage message = new SimpleMailMessage();
        String code = VerifyCode(6);    //随机数生成6位验证码
        message.setFrom(sender);
        message.setTo(email);
        message.setSubject("壮壮招聘网");// 标题
        message.setText("【壮壮招聘网】你的验证码为：" + code + "，有效时间为5分钟(若不是本人操作，可忽略该条邮件)");// 内容
        try {
            javaMailSender.send(message);
            logger.info("文本邮件发送成功！");
            saveCode(code);
            return "success";
        } catch (MailSendException e) {
            logger.error("目标邮箱不存在");
            return "false";
        } catch (Exception e) {
            logger.error("文本邮件发送异常！", e);
            return "failure";
        }

    }

    private String VerifyCode(int n) {
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < n; i++) {
            int ran1 = r.nextInt(10);
            sb.append(String.valueOf(ran1));
        }
        return sb.toString();
    }

    //保存验证码和时间
    private void saveCode(String code) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, 5);
        String currentTime = sf.format(c.getTime());// 生成5分钟后时间，用户校验是否过期

        String hash = MD5Util.getMD5(code);//生成MD5值
        resultMap.put("hash", hash);
        resultMap.put("tamp", currentTime);
    }

    @PostMapping("registe")
    public String myform(String identify,String email, RedirectAttributes attributes,HttpServletRequest request) {

        if (resultMap.size() == 0) {
            return "redirect:/zhuang/reset2";
        }
        //判断验证码是否正确
        String requestHash = resultMap.get("hash").toString();
        String tamp = resultMap.get("tamp").toString();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");//当前时间
        Calendar c = Calendar.getInstance();
        String currentTime = sf.format(c.getTime());
        if (tamp.compareTo(currentTime) > 0) {
            String hash = MD5Util.getMD5(identify);//生成MD5值
            if (hash.equalsIgnoreCase(requestHash)) {
                //校验成功
                attributes.addFlashAttribute("m", "恭喜！现在，你可以登录你的用户名。");
                Company company = companyService.findByUsername(email);
                if (company!=null)
                {
                    HttpSession session = request.getSession();
                    session.setAttribute("company",company);
                    return "redirect:/zhuang/reset";
                }
                Userinfo userinfo = userinfoService.findByUsername(email);
                if (userinfo!=null)
                {
                    HttpSession session = request.getSession();
                    session.setAttribute("userinfo",userinfo);
                    return "redirect:/zhuang/reset";
                }
                if (userinfo==null||company==null)
                {
                    return "redirect:/zhuang/reset2?msg=kong";
                }
                return "redirect:/zhuang/reset2?msg=z";
            } else {
                //验证码不正确，校验失败
                attributes.addFlashAttribute("message", "验证码输入不正确");
                return "redirect:/zhuang/reset2?msg=can";
            }

        } else {
            // 超时
            attributes.addFlashAttribute("message", "验证码已过期");
            return "redirect:/zhuang/reset2?msg=g";
        }
    }
    //登录
    @PostMapping("login")
    public String login(String referer,String type,String rememberMe,String email,String userpass, HttpServletRequest request, HttpServletResponse response)
    {
        if (type==null)
        {
            return "redirect:/zhuang/login?msg=can";

        }
        if (type.equals("0"))
        {
            Userinfo userinfo1 = userinfoService.login(email, userpass);
            if (userinfo1==null)
            {
                return "redirect:/zhuang/login?msg=kong&referer="+referer;
            }
            else
            {
                HttpSession session = request.getSession();
                session.setAttribute("userinfo",userinfo1);
                if (rememberMe!=null)
                {
                    int maxAge = 60*60*24*30;
                    CookieUtil.addCookie("email",email,"/",maxAge,response);
                    userpass = MD5Util.myMD5(userpass);
                    CookieUtil.addCookie("password",userpass,"/",maxAge,response);
                }
                else
                {
                    //删除cookie
                    CookieUtil.addCookie("email", "", "/", 0, response);
                    CookieUtil.addCookie("password", "", "/", 0, response);
                }
                if(StringUtils.isEmpty(referer))
                {
                    return "redirect:/index.jsp";
                }
                else {
                    //如果来路是注册页面则回到首页
                    if(referer.contains("/zhuang/register"))
                    {
                        return "redirect:/index.jsp";
                    }
                    //如果来路是登录页面则回到首页
                    else if (referer.contains("/zhuang/login"))
                    {
                        return "redirect:/index.jsp";
                    }
                    else if (referer.contains("/zhuang/reset"))
                    {
                        return "redirect:/index.jsp";
                    }
                    else {
                        return "redirect:" + referer;
                    }
                }

            }
        }
        if (type.equals("1"))
        {
            Company company = companyService.login(email, userpass);
            if (company==null)
            {
                return "redirect:/zhuang/login?msg=kong&referer="+referer;
            }
            else
            {
                HttpSession session = request.getSession();
                session.setAttribute("company",company);
                if (rememberMe!=null)
                {
                    int maxAge = 60*60*24*30;
                    CookieUtil.addCookie("email",email,"/",maxAge,response);
                    userpass = MD5Util.myMD5(userpass);
                    CookieUtil.addCookie("password",userpass,"/",maxAge,response);
                }
                else
                {
                    //删除cookie
                    CookieUtil.addCookie("email", "", "/", 0, response);
                    CookieUtil.addCookie("password", "", "/", 0, response);
                }
                if(StringUtils.isEmpty(referer))
                {
                    return "redirect:/index.jsp";
                }
                else {
                    //如果来路是注册页面则回到首页
                    if(referer.contains("/zhuang/register"))
                    {
                        return "redirect:/index.jsp";
                    }
                    else if (referer.contains("/zhuang/login"))
                    {
                        return "redirect:/index.jsp";
                    }
                    else if (referer.contains("/zhuang/reset"))
                    {
                        return "redirect:/index.jsp";
                    }
                    else {
                        return "redirect:" + referer;
                    }
                }
                //return "redirect:/index.jsp";
            }
        }
        return "redirect:/zhuang/login";
    }
    //退出
    @RequestMapping("exit")
    public String exit(HttpServletRequest request,HttpServletResponse response)
    {
        ModelAndView modelAndView = new ModelAndView();
        HttpSession session = request.getSession();
        session.removeAttribute("company");
        session.removeAttribute("userinfo");
        CookieUtil.addCookie("email", "", "/", 0, response);
        CookieUtil.addCookie("password", "", "/", 0, response);
        return "redirect:/index.jsp";

    }
    //个人收藏页
    @RequestMapping("user/collections")
    @ModelAttribute("pageInfo")
    public PageInfo<Collection> collections(HttpSession session,Integer pageNum){
        Userinfo loginUser = (Userinfo)session.getAttribute("userinfo");
        if(pageNum==null){
            pageNum = 1;
        }
        PageContext.setPageNum(pageNum);
        PageInfo<Collection> pageInfo = null;
        if(loginUser!=null){
            pageInfo = collectionService.findByUserinfo(loginUser);
        }
        return pageInfo;
    }
    //职位订阅
    @GetMapping("user/subscribe")
    public Model getSubscribe(Model model){
        List<Cycle> cycles = cycleService.findAll();
        model.addAttribute("cycles",cycles);
        List<Industry> industries = industryService.findAll();
        model.addAttribute("industrys",industries);
        List<Province> provinces = provinceService.findAll();
        model.addAttribute("provinces",provinces);
        List<Stage> stages = stageService.findAll();
        model.addAttribute("stages",stages);
        List<Money> monies = moneyService.findAll();
        model.addAttribute("monies",monies);
        return model;
    }
    @PostMapping("user/subscribe")
    public String subscribe(Subscribe subscribe,HttpSession session,HttpServletResponse response) throws ParseException {
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        subscribe.setUserinfo(userinfo);
        Date date =new Date();
        subscribe.setUpdateTime(date);
        if(subscribe.getId()==null){
            subscribeService.insert(subscribe);
            Integer subscribeCount = userinfo.getSubscribeCount();
            subscribeCount++;
            userinfo.setSubscribeCount(subscribeCount);
            session.setAttribute("userinfo",userinfo);
            userinfoService.updateSubscribeCount(userinfo.getId(),1);
            CookieUtil.addCookie("msg","insertSuccess","/",10,response);
            return "redirect:/zhuang/user/subscribeList";
        }
        else{
            subscribeService.update(subscribe);
            CookieUtil.addCookie("msg","updateSuccess","/",10,response);
            return "redirect:/zhuang/user/subscribeList";
        }
    }
    //个人订阅信息
    @RequestMapping("user/subscribeList")
    public Model subscribeList(HttpSession session,Model model,String msg){
        Userinfo userinfo = (Userinfo)session.getAttribute("userinfo");
        Integer userSubscribeCount = null;
        try {
            userSubscribeCount = Integer.parseInt(configService.getValueByKey("user_subscribe_count"));
        } catch (NumberFormatException e) {
            userSubscribeCount = Integer.parseInt(configService.getDefaultValueByKey("user_subscribe_count"));
        }
        List<Subscribe> subscribes = subscribeService.findAllByUserinfo(userinfo);
        model.addAttribute("subscribes",subscribes);
        model.addAttribute("userSubscribeCount",userSubscribeCount);
        model.addAttribute("msg",msg);
        return model;
    }
    //取消订阅
    @RequestMapping("user/cancelSubscribe")
    @ResponseBody
    public void cancelSubscribe(Integer subId,HttpSession session){
        subscribeService.delete(subId);
        Userinfo loginUser = (Userinfo)session.getAttribute("userinfo");
        Integer subscribeCount = loginUser.getSubscribeCount();
        subscribeCount--;
        loginUser.setSubscribeCount(subscribeCount);
        session.setAttribute("userinfo",loginUser);
        userinfoService.updateSubscribeCount(loginUser.getId(),-1);
    }
    //订阅职位推荐
    @RequestMapping("user/recommended")
    public void getRecommonded(){ }
    @RequestMapping("user/recommendedList")
    @ModelAttribute("pageInfo")
    public PageInfo<Job> recommendedList(HttpSession session,Integer pageNum){
        Userinfo loginUser = (Userinfo)session.getAttribute("userinfo");
        List<Subscribe> subscribes = subscribeService.findAllByUserinfo(loginUser);
        if(pageNum==null){
            pageNum = 1;
        }
        PageContext.setPageNum(pageNum);
        return jobService.findRecommend(subscribes);
    }
}
